package com.pioneer.swing.controller;

import com.pioneer.swing.*;
import com.pioneer.beans.*;
import com.pioneer.swing.ui.*;
import com.pioneer.swing.model.*;
import com.pioneer.dao.*;
import com.pioneer.util.AppProperties;
import com.pioneer.util.JobsExporter;
import com.pioneer.dao.DataAccessException;

import javax.swing.JDesktopPane;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.JButton;
import java.text.NumberFormat;
import java.text.DecimalFormat;

import java.awt.Container;
import java.awt.Component;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Vector;

/**
 * Title:        Pioneer Metals
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:      Pioneer Metals
 * @author Gary Chen
 * @version 1.0
 */

public class WindowOpener implements ActionListener {


  private ManifestDAO manifestDAO;
  private ContactDAO jobQuoteContactDAO;
  private ContactDAO metalsContactDAO;	
  private JobDAO jobDAO;
  private JDesktopPane desktopPane;

  public WindowOpener(JDesktopPane desktopPane)
  throws DataAccessException{	
	this.desktopPane = desktopPane;	
  }
	
	public void setManifestDAO(ManifestDAO manifestDAO) {
		this.manifestDAO=manifestDAO;
	}
	
	public void setJobQuoteContactDAO(ContactDAO contactDAO) {
		this.jobQuoteContactDAO = contactDAO;
	}
	
	public void setMetalsContactDAO(ContactDAO contactDAO) {
		this.metalsContactDAO = contactDAO;
	}
	
	public void setJobDAO(JobDAO jobDAO) {
		this.jobDAO = jobDAO;
	}	
	


  public void actionPerformed(ActionEvent e) {
    String actionCommand=e.getActionCommand();
    Object queryObj=e.getSource();	

    if (actionCommand.equals(UIConstants.COMMAND_OPEN_CHAT))  {
		openChat();
    } else if (actionCommand.equals(UIConstants.COMMAND_OPEN_MANIFESTS))  {		
		openManifests();
    }
	else if (actionCommand.equals(UIConstants.COMMAND_OPEN_JOBS))  {		
		openJobs();
    }
	else if ((actionCommand.equals(UIConstants.COMMAND_EDIT_MANIFEST))||
	(actionCommand.equals(UIConstants.COMMAND_NEW_MANIFEST))) {		
		Key key=((Keyed)queryObj).getKey();
		openManifestEntry(key,actionCommand);
	}
	else if (actionCommand.equals(UIConstants.COMMAND_EDIT_JOB)){		
		Key key=((Keyed)queryObj).getKey();
		openJobEntry(key,actionCommand);
	}
	else if (actionCommand.equals(UIConstants.COMMAND_NEW_JOB)){		
		openJobEntry(new JobKey(null),actionCommand);
	}
	else if ((actionCommand.equals(UIConstants.COMMAND_EDIT_CONTAINER))||
	(actionCommand.equals(UIConstants.COMMAND_NEW_CONTAINER))) {
		Key key=((Keyed)queryObj).getKey();
		openContainerEntry(key,actionCommand);
	}
	else if (actionCommand.equals(UIConstants.COMMAND_OPEN_JOBS_CONTACTEDITOR)||actionCommand.equals(UIConstants.COMMAND_OPEN_METALS_CONTACTEDITOR)) {
		JButton button = (JButton)queryObj;
		Component component = button.getTopLevelAncestor();
		Container container = button.getParent().getParent().getParent().getParent();
		this.openContactEditor(actionCommand);		
	}
	else if (actionCommand.equals("comboBoxChanged")){
		String comboBoxName = ((Component)queryObj).getName();				
		if (comboBoxName.equals(UIConstants.COMMAND_NEW_MANIFEST)){
			JComboBox cbox = (JComboBox)queryObj;
			int index = cbox.getSelectedIndex();
			if (index>0){
				String selectedItem = cbox.getSelectedItem().toString();
				Key manifestTypeKey = new ManifestTypeKey(selectedItem);
				openManifestEntry(manifestTypeKey,comboBoxName);
			}
		}		
	}
	else {
		System.err.println("Uncaught action command: "+actionCommand);
		System.exit(0);
	}
  }

	private void openContainerEntry(Key key, String actionCommand)  {

		ContainerEntryFrame mainFrame=new ContainerEntryFrame();
		WindowCloser closer = new WindowCloser();
		closer.setManifestDAO(manifestDAO);
		mainFrame.addInternalFrameListener(closer);
		ContainerContent contents=null;
		ContainerKey containerKey=(ContainerKey)key;
		String jobNum=containerKey.getJobNum();
		String containerId=containerKey.getId();
		String manifestType = containerKey.getManifestType();
		if (containerId==null) {
			// this is the case where the user doesn't select anything
			if (actionCommand.equals(UIConstants.COMMAND_EDIT_CONTAINER))	return;
		}
		else {
			mainFrame.containerIdTextField.setText(containerId);
			try{
				com.pioneer.beans.Container container = manifestDAO.getContainer(jobNum,containerId);
				mainFrame.selectedSupplier = container.getSupplier();
			}
			catch (DataAccessException ex){
				System.err.println("Could not retrieve metals supplier."+ex.getMessage());
			}
			if (actionCommand.equals(UIConstants.COMMAND_EDIT_CONTAINER)) {
				mainFrame.containerIdTextField.setEditable(false);
			}
		}
		mainFrame.jobNumLabel.setText(jobNum);		
		ContainerEntryTable containerEntryTable = null;
		if (manifestType.equals(UIConstants.DROPDOWN_MANIFEST_CHINA)){
			containerEntryTable=new ChinaContainerEntryTable(manifestDAO,key);	
		}
		else if (manifestType.equals(UIConstants.DROPDOWN_MANIFEST_INDONESIA)){
			boolean isNew = actionCommand.equals(UIConstants.COMMAND_NEW_CONTAINER);
			containerEntryTable=new IndonesiaContainerEntryTable(manifestDAO,key,isNew);	
		}
		else{
			containerEntryTable=new ContainerEntryTable(manifestDAO,key);	
		}		
		containerEntryTable.addRow(new Vector());
		mainFrame.deleteButton.addActionListener(new RowRemover(mainFrame.containerContentTable));
		WindowRefresher refresher = new WindowRefresher(desktopPane);
		mainFrame.addInternalFrameListener(refresher);
		refresher.setContactDAO(metalsContactDAO);		
		mainFrame.contactEditorButton.addActionListener(refresher);
		mainFrame.contactEditorButton.addActionListener(this);
		mainFrame.containerContentTable.setModel(containerEntryTable);
		mainFrame.containerContentTable.addKeyListener(new TableRowAdder(mainFrame.containerContentTable));
		// create combo box
		JComboBox fobChoice=new JComboBox();
		fobChoice.addItem("FOB");
		fobChoice.addItem("CNF");
		// Chen asked to remove this column from view
		//mainFrame.containerContentTable.getColumn(
		//"FOB/CNF").setCellEditor(new DefaultCellEditor(fobChoice));

		mainFrame.setSize(600,400);
		updateDesktop(mainFrame,UIConstants.LAYEREDLEVEL_CONTAINER_CONTENT);
  }
	
	
	private void openContactEditor(String actionCommand) {
		try {
			//Properties pathProp = new Properties();
			//pathProp.load(new FileInputStream(FileConstant.CONFIG_PATH+File.separator+FileConstant.PATHPROP));
                        String contactURL="http://localhost:8080";
                        if (actionCommand.equals(UIConstants.COMMAND_OPEN_METALS_CONTACTEDITOR)){
				contactURL = AppProperties.getProperty(AppProperties.METALS_CONTACT_EDITOR_URL);			
                        }
                        else if (actionCommand.equals(UIConstants.COMMAND_OPEN_JOBS_CONTACTEDITOR)){
				contactURL = AppProperties.getProperty(AppProperties.JOB_QUOTE_CONTACT_EDITOR_URL);			
                        }
			String webbrowserCommand = AppProperties.getProperty(AppProperties.WEBBROWSER_COMMAND)+" " +contactURL;
			//System.out.println("Using Web Browser command: "+webbrowserCommand);				
			Runtime.getRuntime().exec(webbrowserCommand);
		}
		catch (java.io.IOException ex) {
			System.err.println("Couldn't load contact editor because: "+ex.getMessage());
		}
				
	}
	
	private void openJobEntry(Key key, String actionCommand)
  {
		JobEntryFrame mainFrame=new JobEntryFrame();
		//mainFrame.setSize(100,200);
		WindowCloser closer = new WindowCloser();
		closer.setJobDAO(jobDAO);
		closer.setContactDAO(jobQuoteContactDAO);
		mainFrame.addInternalFrameListener(closer);
		WindowRefresher refresher = new WindowRefresher(desktopPane);
		refresher.setJobDAO(jobDAO);
		refresher.setContactDAO(jobQuoteContactDAO);
		mainFrame.addInternalFrameListener(refresher);
		RowRemover remover = new RowRemover(mainFrame.itemsTable, mainFrame);
		remover.setJobDAO(jobDAO);
		remover.setContactDAO(jobQuoteContactDAO);
		// for opening up webbrowser
		mainFrame.contactEditorButton.addActionListener(refresher);
		mainFrame.contactEditorButton.addActionListener(this);
		Job job=null;
		// even if user selected a row make it null
		if (actionCommand.equals(UIConstants.COMMAND_NEW_JOB)) {
			//mainFrame.saveJobButton.setEnabled(true);
			   key=new JobKey(null);
		}
		else {
			//mainFrame.saveJobButton.setEnabled(false);			
		}
		// begin setting up dropdowns
		try {
			String[] typeStrings = { "RESIDENTIAL","COMMERCIAL","OTHER" };
			DefaultComboBoxModel types = new DefaultComboBoxModel(typeStrings);
			mainFrame.typeComboBox.setModel(types);
			String[] statusStrings = { "QUOTED", "PENDING", "AWARDED", "CONFIRMED", "SHIPPING","COMPLETED",
				"RE-QUOTE","CANCELLED" };
			DefaultComboBoxModel statuses = new DefaultComboBoxModel(statusStrings);
			mainFrame.statusComboBox.setModel(statuses);

		}
		catch (Exception ex) {
			System.err.println("Cannot populate the drop downs because: "+ex.getMessage());
		}
		// end setting up dropdowns
		
		String [] quoteNums=((JobKey)key).getQuoteNums();
		String quoteNum=null;
		if ((quoteNums!=null) && (quoteNums.length>0)) {
			quoteNum = quoteNums[0];
		}
		if (quoteNum!=null) {
			try {
				job=jobDAO.getJob(quoteNum);
				mainFrame.quoteNumTextField.setText(job.getQuoteNum());
				mainFrame.quoteNumTextField.setEditable(false);
				mainFrame.quoteNumTextField.setFocusable(false);
				mainFrame.jobNameTextField.setText(job.getJobName());
				mainFrame.jobDateTextField.setText(new Job().getJobDateString());
				mainFrame.addressTextField.setText(job.getAddress());
				mainFrame.cityTextField.setText(job.getCity());
				mainFrame.stateTextField.setText(job.getState());
				mainFrame.zipTextField.setText(job.getZip());
				mainFrame.numOfUnitsTextField.setText(job.getQtyString());
				mainFrame.typeComboBox.setSelectedItem(job.getType());
				mainFrame.selectedSalesRep = job.getSalesRep();
				mainFrame.selectedBuilder = job.getBuilderName();
				mainFrame.selectedRegSalesMan = job.getRegSalesMan();
				mainFrame.selectedSupplier = job.getSupplierName();
				//mainFrame.supplierNameComboBox.setSelectedItem(job.getSupplierName());
				//System.out.println("Setting supplier contact to "+job.getSupplierContact());
				mainFrame.supplierContactTextField.setText(job.getSupplierContact());
				//System.out.println("supplier contact set to "+mainFrame.supplierContactTextField.getText());
				mainFrame.selectedContractor = job.getContractorName();
				//mainFrame.contractorNameComboBox.setSelectedItem(job.getContractorName());				
				mainFrame.contractorContactTextField.setText(job.getContractorContact());
				//mainFrame.salesRepComboBox.setSelectedItem(job.getSalesRep());
				mainFrame.statusComboBox.setSelectedItem(job.getStatus());
				mainFrame.shipDateTextField.setText(job.getShipDateString());
				mainFrame.expirationDateTextField.setText(job.getExpirationDateString());
				mainFrame.termsTextField.setText(job.getTerms());
				mainFrame.notesTextField.setText(job.getNotes());
			}
			catch (DataAccessException ex) {
				System.err.println("Couldn't load job for edit because "+ex.getMessage());
			}
		}
		else {
			int increment = 0;
			try {
				String newQuoteNum = KeyGenerator.getQuoteNum(jobDAO.getLastQuoteNum());
				mainFrame.quoteNumTextField.setText(newQuoteNum);				
			}
			catch (DataAccessException ex) {
				System.err.println("Couldn't access job for last quote num because "+ex.getMessage());
			}	
			catch (Exception ex) {
				mainFrame.quoteNumTextField.setText("NEW QUOTE");
				ex.printStackTrace(System.err);
			}
			job = new Job();
			mainFrame.comboBoxInit = true;			
			mainFrame.jobDateTextField.setText(job.getJobDateString());
			//mainFrame.shipDateTextField.setText(job.getShipDateString());
			// this is if the user didn't select anything
			if (actionCommand.equals(UIConstants.COMMAND_EDIT_JOB)) {
				return;
			}
		}
		DefaultTableModel itemEntryTable=null;
		if ((PioneerApp.getCurrentRole().equals(SecurityRoles.ADMINISTRATOR)) ||
			(PioneerApp.getCurrentRole().equals(SecurityRoles.JOBQUOTE_POWERUSER) )){
			itemEntryTable = new AdminItemEntryTable(jobDAO,key);			
		}
		else {
			itemEntryTable = new ItemEntryTable(jobDAO,key);			
			
		}			
		itemEntryTable.addRow(new Vector());		
		mainFrame.deleteButton.addActionListener(new RowRemover(mainFrame.itemsTable));
		mainFrame.itemsTable.setModel(itemEntryTable);
		if (itemEntryTable instanceof ItemEntryTable) {
			mainFrame.itemsTable.getColumnModel().getColumn(ItemEntryTable.ITEM_DESC).setPreferredWidth(500);
		}
		else {
			mainFrame.itemsTable.getColumnModel().getColumn(AdminItemEntryTable.ITEM_DESC).setPreferredWidth(500);
		}		
		mainFrame.itemsTable.addKeyListener(new TableRowAdder(mainFrame.itemsTable));
		mainFrame.setSize(1000,850);        
		updateDesktop(mainFrame,UIConstants.LAYEREDLEVEL_CONTAINER_LIST);
  }	

  private void openManifestEntry(Key key, String actionCommand)
  {
		ManifestEntryFrame mainFrame=new ManifestEntryFrame();
		WindowCloser closer = new WindowCloser();
		closer.setManifestDAO(manifestDAO);
		mainFrame.addInternalFrameListener(closer);
		WindowRefresher refresher = new WindowRefresher(desktopPane);
		refresher.setManifestDAO(manifestDAO);
		mainFrame.addInternalFrameListener(refresher);
		mainFrame.editButton.addActionListener(this);
		mainFrame.newButton.addActionListener(this);
		RowRemover remover = new RowRemover(mainFrame.containerListTable, mainFrame);
		remover.setManifestDAO(manifestDAO);
		mainFrame.deleteButton.addActionListener(remover);
		Saver saver = new Saver(mainFrame);
		saver.setManifestDAO(manifestDAO);
		mainFrame.createManifestButton.addActionListener(saver);
		Manifest manifest=null;
		// even if user selected a row make it null
		if (actionCommand.equals(UIConstants.COMMAND_NEW_MANIFEST)) {
			String selectedItem = ((ManifestTypeKey)key).getManifestType();			
			mainFrame.setManifestType(selectedItem);
			mainFrame.createManifestButton.setEnabled(true);
			mainFrame.newButton.setEnabled(false);
			mainFrame.editButton.setEnabled(false);
			mainFrame.deleteButton.setEnabled(false);
		    key=new ManifestKey(null);
		}
		else {
			mainFrame.createManifestButton.setEnabled(false);
			mainFrame.newButton.setEnabled(true);
			mainFrame.editButton.setEnabled(true);
			mainFrame.deleteButton.setEnabled(true);
		}
		String jobNum=((ManifestKey)key).getJobNum();
		if (jobNum!=null) {
			try {
				manifest=manifestDAO.getManifest(jobNum);				
				mainFrame.jobTextField.setText(manifest.getJobNum());
				mainFrame.setManifestType(manifest.getManifestType());
				mainFrame.jobTextField.setEditable(false);
				mainFrame.jobTextField.setFocusable(false);
				mainFrame.vesselTextField.setText(manifest.getVessel());
				mainFrame.etdTextField.setText(manifest.getEtdString());
				mainFrame.etaTextField.setText(manifest.getEtaString());
				mainFrame.notesTextField.setText(manifest.getContainerNotes());
				NumberFormat numFormat=new DecimalFormat(UIConstants.PATTERN_DEC_FORMAT_2);
				//Float freightFloat=new Float();
				//String formattedFreight=numFormat.format(manifest.getFreightString());
				mainFrame.freightTextField.setText(numFormat.format(manifest.getFreight()));
				mainFrame.truckingTextField.setText(numFormat.format(manifest.getTrucking()));
				mainFrame.miscTextField.setText(numFormat.format(manifest.getMisc()));
			}
			catch (DataAccessException ex) {
				ex.printStackTrace();
			}
		}
		else {
			// this is if the user didn't select anything
			if (actionCommand.equals(UIConstants.COMMAND_EDIT_MANIFEST)) {
				return;
			}
		}
		AllContainersTable allContainersTable=new AllContainersTable(manifestDAO,key);
		mainFrame.containerListTable.setModel(allContainersTable);
		//mainFrame.containerListTable.getSelectionModel().addListSelectionListener(new MultiLineHighlighter(itemEntryTable));
		mainFrame.containerListTable.getColumn(TableConstants.WEIGHT ).setCellRenderer(new HorizontalAlignedCell());
		mainFrame.containerListTable.getColumn(TableConstants.COST).setCellRenderer(new HorizontalAlignedCell());
		mainFrame.containerListTable.getColumn(TableConstants.FOB_C_NUM).setCellRenderer(new HorizontalAlignedCell());
		mainFrame.containerListTable.getColumn(TableConstants.FOB_AMOUNT).setCellRenderer(new HorizontalAlignedCell());
		//System.out.println(mainFrame.containerListTable.getColumnClass(6).getName());
		mainFrame.setSize(720,700);
        
		updateDesktop(mainFrame,UIConstants.LAYEREDLEVEL_CONTAINER_LIST);
  }

  private void openManifests()
  {
		ManifestsFrame mainFrame=new ManifestsFrame();
		WindowCloser closer = new WindowCloser();
		closer.setManifestDAO(manifestDAO);
		mainFrame.addInternalFrameListener(closer);
		WindowRefresher refresher = new WindowRefresher(desktopPane);
		refresher.setManifestDAO(manifestDAO);
		mainFrame.addInternalFrameListener(refresher);
		mainFrame.editButton.addActionListener(this);
		mainFrame.newComboBox.addActionListener(this);
		String[] typeStrings = { "New Manifest Type:",UIConstants.DROPDOWN_MANIFEST_CHINA,
		UIConstants.DROPDOWN_MANIFEST_INDONESIA};
		DefaultComboBoxModel types = new DefaultComboBoxModel(typeStrings);
		mainFrame.newComboBox.setModel(types);
			
		RowRemover remover = new RowRemover(mainFrame.manifestTable, mainFrame);
		remover.setManifestDAO(manifestDAO);
		mainFrame.deleteButton.addActionListener(remover);
		
		Printer printer = new Printer();
		printer.setManifestDAO(manifestDAO);
		mainFrame.printButton.addActionListener(printer);
		mainFrame.manifestTable.setModel(new AllManifestsTable(manifestDAO));
		mainFrame.setSize(600,400);
		updateDesktop(mainFrame,UIConstants.LAYEREDLEVEL_MANIFEST_LIST);		
		
  }
	
private void openJobs()
  {
		JobsFrame mainFrame=new JobsFrame();
		WindowCloser closer = new WindowCloser();
		closer.setJobDAO(jobDAO);
		mainFrame.addInternalFrameListener(closer);		
		WindowRefresher refresher = new WindowRefresher(desktopPane);
		refresher.setManifestDAO(manifestDAO);
		mainFrame.addInternalFrameListener(refresher);		
		mainFrame.editButton.addActionListener(this);
		mainFrame.newButton.addActionListener(this);
		RowRemover remover = new RowRemover(mainFrame.jobTable, mainFrame);
		remover.setJobDAO(jobDAO);
		mainFrame.deleteButton.addActionListener(remover);
		Printer printer = new Printer();
		printer.setJobDAO(jobDAO);
		printer.setContactDAO(jobQuoteContactDAO);
		mainFrame.printButton.addActionListener(printer);
		try {
			JobsExporter exporter = new JobsExporter(AppProperties.getProperties());
			mainFrame.exportButton.addActionListener(exporter);
		}
		catch (DataAccessException ex) {
			ex.printStackTrace(System.err);
		}
		mainFrame.jobTable.setModel(new AllJobsTable(jobDAO));
		JTableHeader th = mainFrame.jobTable.getTableHeader();
		TableSorter sorter = new TableSorter(mainFrame.jobTable);
		mainFrame.jobTable.getColumnModel().getColumn(AllJobsTable.JOB_QUOTE_NUM).setPreferredWidth(60);
		mainFrame.jobTable.getColumnModel().getColumn(AllJobsTable.JOB_STATE).setPreferredWidth(40);
		mainFrame.jobTable.getColumnModel().getColumn(AllJobsTable.JOB_NAME).setPreferredWidth(150);
		mainFrame.jobTable.getColumnModel().getColumn(AllJobsTable.JOB_CONTRACTOR).setPreferredWidth(150);
		mainFrame.jobTable.getColumnModel().getColumn(AllJobsTable.JOB_WHOLESALER).setPreferredWidth(150);
		mainFrame.jobTable.getColumnModel().getColumn(AllJobsTable.JOB_SALES_REP).setPreferredWidth(100);
		mainFrame.jobTable.getColumnModel().getColumn(AllJobsTable.JOB_NOTES).setPreferredWidth(150);
		th.addMouseListener(sorter);
		mainFrame.setSize(1000,600);
		updateDesktop(mainFrame,UIConstants.LAYEREDLEVEL_JOB_LIST);		
  }

  private void openChat()
  {
		String chatPortStr = AppProperties.getProperty(AppProperties.CHAT_PORT);
		int chatPort = Integer.parseInt(chatPortStr);
		String chatServer = AppProperties.getProperty(AppProperties.CHAT_SERVER);
		
		ChatFrame mainFrame=new ChatFrame(chatServer,chatPort);
		//mainFrame.addInternalFrameListener(mainFrame);
		//WindowRefresher refresher = new WindowRefresher(desktopPane);
		//refresher.setManifestDAO(manifestDAO);
		//mainFrame.addInternalFrameListener(refresher);
		//mainFrame.editButton.addActionListener(this);
		//mainFrame.newButton.addActionListener(this);
		
		//RowRemover remover = new RowRemover(mainFrame.manifestTable, mainFrame);
		//remover.setManifestDAO(manifestDAO);
		//mainFrame.deleteButton.addActionListener(remover);
		
		//Printer printer = new Printer();
		//printer.setManifestDAO(manifestDAO);
		//mainFrame.printButton.addActionListener(printer);
		//mainFrame.userList.setModel(new AllUsersTable());		
		mainFrame.setSize(600,400);
		updateDesktop(mainFrame,UIConstants.LAYEREDLEVEL_CHAT);		
		
  }
	
  private void updateDesktop(JInternalFrame frame,int level) {
		frame.setLocation(level*1,level*1);
		desktopPane.add(frame,new Integer(level));
		try {
			frame.setVisible(true);
			frame.setSelected(true);
		}
		catch (java.beans.PropertyVetoException e) {
			System.err.println("Veto Exception: "+e.getMessage());
		}
	}
}
